package com.cn.longdistancebusstation.scenic.order;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.global.GlobalVariable;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.CancleOrder;
import com.cn.longdistancebusstation.model.Contacter;
import com.cn.longdistancebusstation.model.Identification;
import com.cn.longdistancebusstation.model.ListResultIII;
import com.cn.longdistancebusstation.model.ListResultV;
import com.cn.longdistancebusstation.model.Result;
import com.cn.longdistancebusstation.model.ScenicOrder;
import com.cn.longdistancebusstation.model.ScenicOrderDetails;
import com.cn.longdistancebusstation.model.SubmitPftOrder;
import com.cn.longdistancebusstation.scenic.ScenicListActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by mucheng on 2018/3/30.
 */

public class PrePayOrderDetailsActivity extends BaseActivity implements View.OnClickListener{
//    private TextView mTimeTextView;
    private String ticketId,qrcodeIMG,qrcodeURL,remotenum,code,ordernum,orderTime,scenicName,scenicId,ticketName,ticketAmount,ticketAmountPrice;
    private String touristName,touristCardNo,touristTelephone;
    private Date mLatestPayDate;
    private Timer mTimer;
    private TextView mOrderStatusTextView;
    private TextView mScenicName,mTicketAmountPrice;
    private TextView mOrderId,mOrderTime;
    private Button mPayOrderBtn,mCancleOrderBtn;
    private ImageView mScheduleNote;
    private int num=1;
    private CancleOrder mCancleOrder;
    private String strUUdone;
    private RecyclerView mRecyclerView;
    private TouristInfoAdapter mTouristInfoAdapter;
    private String touristNum;
    private String scenicImage;
    private ArrayList<Contacter> mArrayList=new ArrayList<>();
    private Map<String,String> params;
    private String orderId;
    private Contacter contacter;
    private String aid;
    private String ticketPrice;
    private BigDecimal ma;
    private BigDecimal mb;
    private BigDecimal mc;
    private BigDecimal mul;
    private BigDecimal mul2;
    private int number=100;
    private SubmitPftOrder mSubmitPftOrder;
    private String str_orderTime;
    private ScenicOrderDetails mScenicOrderDetails;
    private ArrayList<Contacter> mContacterList=new ArrayList<>();
    private LinearLayout mPrePayLinearLayout;
    private LinearLayout mAfterPaymentLinearLayout;
    private ImageView mQrcodeImageView;
    private TextView mVoucherTextView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pre_pay_order_details2);
        getTitleTextView().setText("订单详情");
        initView();
        getOrderDetails();
        registerBroadcast();
    }

    private void initView() {
        Intent in=getIntent();
        ticketId=in.getStringExtra("ticketId");
        mArrayList= (ArrayList<Contacter>) in.getSerializableExtra("contacter");
        orderId=in.getStringExtra("orderId");
        mScenicName=(TextView)findViewById(R.id.ticket_name);
        mTicketAmountPrice=(TextView)findViewById(R.id.ticket_amount_price);
        mOrderId=(TextView)findViewById(R.id.ticket_number);
        mOrderTime=(TextView)findViewById(R.id.order_time);
        mPayOrderBtn=(Button)findViewById(R.id.button_pay);
        mPayOrderBtn.setOnClickListener(this);
        mCancleOrderBtn=(Button)findViewById(R.id.button_cancle_order);
        mCancleOrderBtn.setOnClickListener(this);
        mScheduleNote=(ImageView)findViewById(R.id.order_note);
        mScheduleNote.setOnClickListener(this);
        mRecyclerView=(RecyclerView)findViewById(R.id.tourist_list);
        mTouristInfoAdapter=new TouristInfoAdapter();
        mRecyclerView.setAdapter(mTouristInfoAdapter);
        mOrderStatusTextView=(TextView)findViewById(R.id.ticket_status);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        for(int i=0;i<mArrayList.size();i++){
            touristName=mArrayList.get(i).getName();
            touristCardNo=mArrayList.get(i).getCardNo();
            touristTelephone=mArrayList.get(i).getTelephone();
        }
    }
    private void getOrderDetails() {
        showHud();
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService service=retrofit.create(HttpService.class);
        Call<ListResultV<ScenicOrderDetails>> call=service.getScenicOrderDetails(orderId);
        call.enqueue(new Callback<ListResultV<ScenicOrderDetails>>() {
            @Override
            public void onResponse(Call<ListResultV<ScenicOrderDetails>> call, Response<ListResultV<ScenicOrderDetails>> response) {
                hideHud();
                ListResultV listResultV=response.body();
                if(listResultV!=null){
                    if(listResultV.getHead().getSuccess()) {
                        Gson gson = new Gson();
                        Map<String, String> scenicMap = listResultV.getBody().getData();
                        Type type = new TypeToken<ScenicOrderDetails>() {
                        }.getType();
                        String strScenicOrderJSON = new Gson().toJson(scenicMap);
                        mScenicOrderDetails = gson.fromJson(strScenicOrderJSON, type);
                        if("0".equals(mScenicOrderDetails.getStatus())){
                            mOrderStatusTextView.setText("待付款");
                        }else if("1".equals(mScenicOrderDetails.getStatus())){
                            mOrderStatusTextView.setText("待使用");
                        }else if("2".equals(mScenicOrderDetails.getStatus())){
                            mOrderStatusTextView.setText("已取消");
                        }else if("3".equals(mScenicOrderDetails.getStatus())){
                            mOrderStatusTextView.setText("已使用");
                        }else if("4".equals(mScenicOrderDetails.getStatus())){
                            mOrderStatusTextView.setText("已退款");
                        }else if("5".equals(mScenicOrderDetails.getStatus())){
                            mOrderStatusTextView.setText("订单异常");
                        }else if("6".equals(mScenicOrderDetails.getStatus())){
                            mOrderStatusTextView.setText("退款待审核");
                        }else{
                            mOrderStatusTextView.setText("退款失败");
                        }

                        mScenicName.setText(mScenicOrderDetails.getPltitle()+mScenicOrderDetails.getTtitle()+mScenicOrderDetails.getNum());
                        ticketAmount=mScenicOrderDetails.getTotalPrice();
                        mTicketAmountPrice.setText(ticketAmount+"元");
                        mOrderId.setText(mScenicOrderDetails.getOrderId());
                        mOrderTime.setText(mScenicOrderDetails.getCreateTime());
                        touristName=mScenicOrderDetails.getOrdername();
                        touristCardNo=mScenicOrderDetails.getOrderId();
                        touristTelephone=mScenicOrderDetails.getOrdertel();

                        String[] names = touristName.split(",");
                        String[] phones = touristTelephone.split(",");
                        String[] cardNos = touristCardNo.split(",");

                        for(int i=0; i<names.length; i++)
                        {
                            String strName = names[i];
                            String strPhone = phones[i];
                            String strCardNo = cardNos[i];
                            Contacter contacter = new Contacter();

                            contacter.setName(strName);
                            contacter.setTelephone(strPhone);
                            contacter.setCardNo(strCardNo);
                            mContacterList.add(contacter);
                        }
                        mTouristInfoAdapter.notifyDataSetChanged();

                    }

                }

            }

            @Override
            public void onFailure(Call<ListResultV<ScenicOrderDetails>> call, Throwable t) {
                hideHud();
                Toast.makeText(PrePayOrderDetailsActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.button_pay:
                payOrder();
                break;
            case R.id.order_note:
                note();
                break;
            case R.id.button_cancle_order:
                cancleOrder();
                break;
        }

    }

    private void note() {
        Intent intent=new Intent(PrePayOrderDetailsActivity.this,ScheduleNoteActivity.class);
        startActivity(intent);
    }

    private void payOrder() {
//        showHud();
//        params=new HashMap<>();
//        params.put("searchParam.userId", GlobalVariable.getUserID());
//        params.put("searchParam.lid",mScenicOrderDetails.getPlid());
//        params.put("searchParam.tid",ticketId);
//        params.put("searchParam.ltitle",mScenicOrderDetails.getPltitle());
//        params.put("searchParam.ttitle",mScenicOrderDetails.getTtitle());
//        params.put("searchParam.remotenum",pftId);
//        params.put("searchParam.tprice", mScenicOrderDetails.getTprice());
//        params.put("searchParam.tnum", mScenicOrderDetails.getNum());
//        params.put("searchParam.playtime", mScenicOrderDetails.getPlaytime());
//        StringBuilder strNames = new StringBuilder();
//        StringBuilder strCardNos = new StringBuilder();
//        StringBuilder strPhones = new StringBuilder();
//        if(mArrayList.size()!=0) {
//            for (int i = 0; i < mArrayList.size(); i++) {
//                contacter = mArrayList.get(i);
//                String cardNO = contacter.getCardNo();
//                SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
//                editor.putString("cardNO", cardNO);
//                editor.commit();
//                if (i == 0) {
//                    strNames.append(contacter.getName());
//                    strCardNos.append(contacter.getCardNo());
//                    strPhones.append(contacter.getTelephone());
//                } else {
//                    strNames.append("," + contacter.getName());
//                    strCardNos.append("," + contacter.getCardNo());
//                    strPhones.append("," + contacter.getCoupons());
//                }
//            }
//        }
//        params.put("searchParam.ordername",strNames.toString());
//        params.put("searchParam.ordertel",strPhones.toString());
//        params.put("searchParam.aid",mScenicOrderDetails.getAid());
//        params.put("searchParam.personID",strCardNos.toString());
//        params.put("searchParam.totalPrice", mScenicOrderDetails.getTotalPrice());
//        params.put("searchParam.imagePath",mScenicOrderDetails.getImagePath());
//        params.put("searchParam.memo","");
//        Log.d("参数",params.toString());
//        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
//        HttpService httpService=retrofit.create(HttpService.class);
//        Call<ListResultIII<SubmitPftOrder>> call=httpService.submitPftOrder(params);
//        call.enqueue(new Callback<ListResultIII<SubmitPftOrder>>() {
//            @Override
//            public void onResponse(Call<ListResultIII<SubmitPftOrder>> call, Response<ListResultIII<SubmitPftOrder>> response) {
//                hideHud();
//                ListResultIII result=response.body();
//                if(result.getHead().getSuccess()) {
//                    Gson gson = new Gson();
//                    Map<String, List<SubmitPftOrder>> scenicMap = result.getBody().getData();
//                    List<SubmitPftOrder> list = scenicMap.get("Rec");
//
//                    Type type = new TypeToken<SubmitPftOrder>() {
//                    }.getType();
//                    String strScenicJSON = new Gson().toJson(list.get(0));
//                    mSubmitPftOrder=gson.fromJson(strScenicJSON, type);
//                    qrcodeIMG=mSubmitPftOrder.getUUqrcodeIMG();
//                    qrcodeURL=mSubmitPftOrder.getUUqrcodeURL();
//                    remotenum=mSubmitPftOrder.getUUremotenum();
//                    code=mSubmitPftOrder.getUUcode();
//                    ordernum=mSubmitPftOrder.getUUordernum();
//                    str_orderTime=mSubmitPftOrder.getOrderTime();
            Intent in=new Intent(PrePayOrderDetailsActivity.this, TicketOrderPaymentActivity.class);
            in.putExtra("orderNo",orderId);
            in.putExtra("orderId",orderId);
            in.putExtra("scenicName",mScenicOrderDetails.getPltitle());
            in.putExtra("ticketName",mScenicOrderDetails.getTtitle());
            in.putExtra("totalAmount",mScenicOrderDetails.getTotalPrice());
            in.putExtra("plid",mScenicOrderDetails.getPlid());

            startActivity(in);

//                }else{
//
//                }
//            }
//
//            @Override
//            public void onFailure(Call<ListResultIII<SubmitPftOrder>> call, Throwable t) {
//                hideHud();
//                Toast.makeText(PrePayOrderDetailsActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
//
//
//            }
//        });

    }
    private void cancleOrder() {
        showHud("正在取消订单，请稍后");
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService=retrofit.create(HttpService.class);
        Call<Result> call=httpService.getCancleOrder(orderId);
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                hideHud();
                Gson gson=new Gson();
                Result result=response.body();
                Boolean isSuccess=result.getHead().getSuccess();
                if(isSuccess){
                    Toast.makeText(PrePayOrderDetailsActivity.this,"取消订单成功",Toast.LENGTH_SHORT).show();
                    finish();
                }else{
                    Toast.makeText(PrePayOrderDetailsActivity.this,"取消订单失败",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                hideHud();
                Toast.makeText(PrePayOrderDetailsActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }

    private class TouristInfoAdapter extends RecyclerView.Adapter<TouristInfoViewHolder>{
        @Override
        public TouristInfoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(PrePayOrderDetailsActivity.this);
            View view = layoutInflater.inflate(R.layout.tourist_info_recycle_item, parent, false);
            return new TouristInfoViewHolder(view);
        }

        @Override
        public void onBindViewHolder(TouristInfoViewHolder holder, int position) {
            Contacter contacter=mArrayList.get(position);
            holder.bindData(contacter);

        }

        @Override
        public int getItemCount() {
            return mArrayList.size();
        }
    }

    private class TouristInfoViewHolder extends RecyclerView.ViewHolder{
        private TextView mTouristNameTextView;
        private TextView mTouristIdcardNoTextView;
        private TextView mtouristTelephoneTextView;
        public TouristInfoViewHolder(View itemView) {
            super(itemView);
            mTouristNameTextView=(TextView)itemView.findViewById(R.id.tourist_name);
            mTouristIdcardNoTextView=(TextView)itemView.findViewById(R.id.idcard_numbers);
            mtouristTelephoneTextView=(TextView)itemView.findViewById(R.id.telephone_number);
        }

        public void bindData(Contacter contacter) {
            mTouristNameTextView.setText(contacter.getName());
            mTouristIdcardNoTextView.setText(contacter.getCardNo());
            mtouristTelephoneTextView.setText(contacter.getTelephone());

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getOrderDetails();

    }
    MyReceiver receiver;
    private void registerBroadcast() {
        // 注册广播接收者
        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("close_current_boundary");
        this.registerReceiver(receiver,filter);
    }
    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("close_current_boundary")){
                finish();
            }
        }
    }
}
